package showtime.framework.log
{
	import flash.utils.describeType;
	
	/** 
	 * @project showtime
	 * @author yinhao
	 * @date 2011-4-7
	 *
	 */
	
	public class LoggingData
	{
		private var _level:Level = null;
		
		private var _message:Array = null;
		
		private var _timeStamp:String = null;
		
		private var _code:String = null;
		
		public function LoggingData(level:Level, message:Array)
		{
			_level = level;
			
			_message = message;
			
			_timeStamp = null;
		}
		
		private static function escapeString(target:String):String
		{
			return "\"" + target + "\"";
		}
		
		private static function objectToString(target:Object):String
		{
			var code:String = "";
			
			var classInfo:XML = describeType(target);
			
			var name:String = classInfo.@name.toString().replace(/::/, ".");
			
			if (name == "Object")
			{
				var value:Object = null;
				
				for (var key:String in target)
				{
					value = target[key];
					
					if (value is Function)
					{
						continue;
					}
					if (code.length > 0)
					{
						code += ",";
					}
					code += key + ":" + LoggingData.encode(value);
				}
			}
			else
			{
				return "[" + name + "]";
			}
			
			return "{" + code + "}";
		}
		
		private static function arrayToString(target:Array):String
		{
			var code:String = "";
			
			var len:int = target.length;
			
			for (var i:int = 0; i < len; i++)
			{
				if (code.length > 0)
				{
					code += ",";
				}
				
				code += LoggingData.encode(target[i]);
			}
			
			return "[" + code + "]";
		}
		
		private static function encode(target:*):String
		{
			if (target is String)
			{
				return LoggingData.escapeString(String(target));
			}
			else if (target is Number)
			{
				return isFinite(Number(target)) ? target : "null";
			}
			else if (target is Array)
			{
				return LoggingData.arrayToString(target as Array);
			}
			else if (target is Object && target != null)
			{
				return LoggingData.objectToString(target);
			}
			
			return "null";
		}
		
		public function get level():Level
		{
			return _level;
		}
		
		public function get message():Array
		{
			return _message;
		}
		
		public static function toCode(target:Array):String
		{
			var result:String = "null";
			
			if (target != null)
			{
				result = "";
				
				for each (var item:* in target)
				{
					if (result.length > 0)
					{
						result += " ";
					}
					
					result += LoggingData.encode(item);
				}
			}
			
			return result;
		}
		
		public function toString():String
		{
			if (_code == null)
			{
				_code = LoggingData.toCode(_message);
			}
			
			return _code;
		}
	}
}